import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAppStore = defineStore('app', () => {
  // 状态
  const loading = ref(false)
  const networkStatus = ref(true)
  const pageVisible = ref(true)
  const sidebarCollapsed = ref(false)
  const globalSearchVisible = ref(false)
  const theme = ref('light')
  const language = ref('zh-CN')
  const pageVisits = ref({})
  const notifications = ref([])
  const modals = ref({
    imageViewer: false,
    videoPlayer: false,
    confirm: false,
    message: false
  })

  // 设备信息
  const device = ref({
    isMobile: false,
    isTablet: false,
    isDesktop: true,
    userAgent: navigator.userAgent
  })

  // 应用配置
  const config = ref({
    apiBaseUrl: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080',
    uploadUrl: import.meta.env.VITE_UPLOAD_URL || 'http://localhost:8080/upload',
    wsUrl: import.meta.env.VITE_WS_URL || 'ws://localhost:8080/ws',
    version: '1.0.0',
    buildTime: new Date().toISOString()
  })

  // 计算属性
  const isOnline = computed(() => networkStatus.value)
  const isMobile = computed(() => device.value.isMobile)
  const isTablet = computed(() => device.value.isTablet)
  const isDesktop = computed(() => device.value.isDesktop)
  const isDark = computed(() => theme.value === 'dark')
  const totalPageVisits = computed(() => {
    return Object.values(pageVisits.value).reduce((total, count) => total + count, 0)
  })

  // 方法
  const setLoading = (status) => {
    loading.value = status
  }

  const setNetworkStatus = (status) => {
    networkStatus.value = status
  }

  const setPageVisible = (visible) => {
    pageVisible.value = visible
  }

  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
    // 保存到本地存储
    localStorage.setItem('sidebarCollapsed', sidebarCollapsed.value)
  }

  const setSidebarCollapsed = (collapsed) => {
    sidebarCollapsed.value = collapsed
    localStorage.setItem('sidebarCollapsed', collapsed)
  }

  const toggleGlobalSearch = () => {
    globalSearchVisible.value = !globalSearchVisible.value
  }

  const setGlobalSearchVisible = (visible) => {
    globalSearchVisible.value = visible
  }

  const setTheme = (newTheme) => {
    theme.value = newTheme
    localStorage.setItem('theme', newTheme)
    // 更新 HTML 类名
    document.documentElement.className = newTheme
  }

  const setLanguage = (lang) => {
    language.value = lang
    localStorage.setItem('language', lang)
  }

  const recordPageVisit = (path) => {
    if (pageVisits.value[path]) {
      pageVisits.value[path]++
    } else {
      pageVisits.value[path] = 1
    }
    // 保存到本地存储
    localStorage.setItem('pageVisits', JSON.stringify(pageVisits.value))
  }

  const addNotification = (notification) => {
    const id = Date.now().toString()
    notifications.value.unshift({
      id,
      ...notification,
      timestamp: new Date(),
      read: false
    })
    
    // 限制通知数量
    if (notifications.value.length > 100) {
      notifications.value = notifications.value.slice(0, 100)
    }
    
    // 保存到本地存储
    localStorage.setItem('notifications', JSON.stringify(notifications.value))
  }

  const markNotificationAsRead = (id) => {
    const notification = notifications.value.find(n => n.id === id)
    if (notification) {
      notification.read = true
      localStorage.setItem('notifications', JSON.stringify(notifications.value))
    }
  }

  const markAllNotificationsAsRead = () => {
    notifications.value.forEach(n => n.read = true)
    localStorage.setItem('notifications', JSON.stringify(notifications.value))
  }

  const removeNotification = (id) => {
    const index = notifications.value.findIndex(n => n.id === id)
    if (index > -1) {
      notifications.value.splice(index, 1)
      localStorage.setItem('notifications', JSON.stringify(notifications.value))
    }
  }

  const clearAllNotifications = () => {
    notifications.value = []
    localStorage.removeItem('notifications')
  }

  const openModal = (modalName) => {
    if (modals.value.hasOwnProperty(modalName)) {
      modals.value[modalName] = true
    }
  }

  const closeModal = (modalName) => {
    if (modals.value.hasOwnProperty(modalName)) {
      modals.value[modalName] = false
    }
  }

  const closeAllModals = () => {
    Object.keys(modals.value).forEach(key => {
      modals.value[key] = false
    })
  }

  const detectDevice = () => {
    const width = window.innerWidth
    device.value.isMobile = width < 768
    device.value.isTablet = width >= 768 && width < 1024
    device.value.isDesktop = width >= 1024
  }

  const initApp = async () => {
    try {
      // 从本地存储恢复状态
      const savedTheme = localStorage.getItem('theme')
      if (savedTheme) {
        setTheme(savedTheme)
      }

      const savedLanguage = localStorage.getItem('language')
      if (savedLanguage) {
        setLanguage(savedLanguage)
      }

      const savedSidebarState = localStorage.getItem('sidebarCollapsed')
      if (savedSidebarState !== null) {
        setSidebarCollapsed(JSON.parse(savedSidebarState))
      }

      const savedPageVisits = localStorage.getItem('pageVisits')
      if (savedPageVisits) {
        pageVisits.value = JSON.parse(savedPageVisits)
      }

      const savedNotifications = localStorage.getItem('notifications')
      if (savedNotifications) {
        notifications.value = JSON.parse(savedNotifications)
      }

      // 检测设备类型
      detectDevice()
      window.addEventListener('resize', detectDevice)

      // 检测网络状态
      setNetworkStatus(navigator.onLine)
      window.addEventListener('online', () => setNetworkStatus(true))
      window.addEventListener('offline', () => setNetworkStatus(false))

      console.log('应用初始化完成')
    } catch (error) {
      console.error('应用初始化失败:', error)
      throw error
    }
  }

  const refreshCurrentPageData = () => {
    // 页面重新可见时刷新数据的逻辑
    console.log('刷新当前页面数据')
  }

  return {
    // 状态
    loading,
    networkStatus,
    pageVisible,
    sidebarCollapsed,
    globalSearchVisible,
    theme,
    language,
    pageVisits,
    notifications,
    modals,
    device,
    config,
    
    // 计算属性
    isOnline,
    isMobile,
    isTablet,
    isDesktop,
    isDark,
    totalPageVisits,
    
    // 方法
    setLoading,
    setNetworkStatus,
    setPageVisible,
    toggleSidebar,
    setSidebarCollapsed,
    toggleGlobalSearch,
    setGlobalSearchVisible,
    setTheme,
    setLanguage,
    recordPageVisit,
    addNotification,
    markNotificationAsRead,
    markAllNotificationsAsRead,
    removeNotification,
    clearAllNotifications,
    openModal,
    closeModal,
    closeAllModals,
    detectDevice,
    initApp,
    refreshCurrentPageData
  }
})
